<template>
  <div class="dashboard-container">
    <div class="app-container">
      <page-tools>
        <template #slot-left>
          <span>共19条记录</span>
        </template>

        <template #slot-right>
          <el-button v-power="'import'" type="danger" size="small" @click="$router.push('/excel')">导入excel</el-button>
          <el-button v-power="'export'" type="success" size="small" @click="downloadExcel">导出excel</el-button>
          <el-button
            type="primary"
            size="small"
            @click="showDialog=true"
          >新增员工</el-button>
        </template>
      </page-tools>

      <el-card style="margin-top: 10px;">
        <el-table
          border
          style="width:100%"
          :data="employeesList"
          :default-sort="{prop: 'workNumber'}"
        >
          <el-table-column label="序号" type="index" width="80" />
          <el-table-column label="姓名" prop="username" />
          <el-table-column label="头像" prop="staffPhoto">
            <template v-slot="scope">
              <!-- <img :src="scope.row.staffPhoto" class="staffphoto"> -->
              <image-holder :src="scope.row.staffPhoto" class="staffphoto" />
            </template>
          </el-table-column>
          <el-table-column label="手机号" prop="mobile" sortable />
          <el-table-column label="工号" prop="workNumber" sortable />
          <el-table-column label="聘用形式" prop="formOfEmployment" :formatter="formatter" />
          <el-table-column label="部门" prop="departmentName" />
          <el-table-column label="入职时间" prop="timeOfEntry" sortable>
            <template slot-scope="scope">
              <span>{{ scope.row.timeOfEntry | formatTime }}</span>
            </template>
          </el-table-column>
          <el-table-column label="转正时间" prop="correctionTime" sortable>
            <template slot-scope="scope">
              <span>{{ scope.row.correctionTime | formatTime }}</span>
            </template>
          </el-table-column>
          <el-table-column label="操作" width="200">
            <template slot-scope="scope">
              <el-button type="text" size="small" @click="$router.push('/employees/detail?id=' + scope.row.id)">查看</el-button>
              <el-button type="text" size="small" @click="setRole(scope.row.id)">分配角色</el-button>
              <el-button type="text" size="small" @click="delEmp(scope.row.id)">删除</el-button>
            </template>
          </el-table-column>
        </el-table>

        <!-- 分页组件 -->
        <el-pagination
          :current-page="query.page"
          :page-sizes="[10, 15, 20, 25]"
          :page-size="query.size"
          layout="total, sizes, prev, pager, next, jumper"
          :total="total"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />

        <!-- 新增员工弹框组件 -->
        <el-dialog
          title="新增员工"
          :visible.sync="showDialog"
          width="50%"
          @close="closeDialog"
        >
          <emp-dialog ref="addEmpt" @close="showDialog=false" @update-list="updateList" />
        </el-dialog>

        <!-- 分配角色弹框 -->
        <el-dialog
          title="分配角色"
          :visible.sync="showRoleDialog"
          width="50%"
        >
          <assign-role v-if="showRoleDialog" :role-id="roleId" @close="showRoleDialog=false" />
        </el-dialog>
      </el-card>
    </div>
  </div>
</template>

<script>
import { getEmployeeList, delEmployee } from '@/api/employees'
// 引入弹框
import EmpDialog from './empDialog.vue'

// 引入日期格式化方法
import dayjs from 'dayjs'

// 导入枚举数据
import Employeenum from '@/constant/employees'

// 引入弹框组件
import AssignRole from './assignRole.vue'

export default {
  name: 'Employees',
  components: {
    EmpDialog,
    AssignRole
  },

  // 创建格式化入职日期的过滤器
  filters: {
    formatTime(time) {
      return dayjs(time).format('YYYY-MM-DD')
    }
  },
  data() {
    return {
      query: {
        page: 1, // 页码
        size: 10 // 每页显示条数
      },
      total: 0, // 数据总条数
      employeesList: [],
      showDialog: false, // 新增员工弹框展示
      showRoleDialog: false, // 分配角色弹框展示
      roleId: ''
    }
  },

  created() {
    this.getEmployeeList()
  },

  methods: {
    // 关闭分配角色弹框
    cancleDialog() {
      this.showRoleDialog = false
    },

    // 点击展示分配角色弹框并传递id
    setRole(id) {
      this.showRoleDialog = true
      this.roleId = id
    },

    transData(rows) {
      // 定义一份枚举的数据
      const map = {
        'id': '编号',
        'password': '密码',
        'mobile': '手机号',
        'username': '姓名',
        'timeOfEntry': '入职日期',
        'formOfEmployment': '聘用形式',
        'correctionTime': '转正日期',
        'workNumber': '工号',
        'departmentName': '部门',
        'staffPhoto': '头像地址'
      }

      // 格式化表头
      const headerArr = Object.keys(rows[0])
      const header = headerArr.map(item => {
        return map[item]
      })

      // 格式化具体数据
      const data = rows.map(item => {
        return Object.values(item)
      })

      return { header, data }
    },

    async downloadExcel() {
      // 调用获取员工列表API
      const res = await getEmployeeList(this.query)

      // 格式化得到的数据
      const excelObj = this.transData(res.data.rows)

      import('@/vendor/Export2Excel').then(excel => {
        // 准备导出的数据
        // const tHeader = ['Id', 'Title', 'Author', 'Readings', 'Date']
        // const filterVal = ['id', 'title', 'author', 'pageViews', 'display_time']
        // const list = this.list
        // const data = this.formatJson(filterVal, list)

        // const header = ['序号', '姓名', '性别', '年龄']
        // const data = [
        //   ['1', '张飞', '男', '20'],
        //   ['2', '关羽', '男', '33'],
        //   ['3', '刘备', '男', '36']
        // ]

        // 调用文件，插件提供的导出excel方法
        excel.export_json_to_excel({
          header: excelObj.header, // 表头 必填
          data: excelObj.data, // 具体数据 必填
          filename: '员工列表', // 非必填
          autoWidth: true, // 非必填
          bookType: 'xlsx' // 非必填
        })
      })
    },

    // 监听弹窗关闭
    closeDialog() {
      this.$refs.addEmpt.resetForm()
    },

    // 新增员工更新列表
    updateList() {
      this.showDialog = false
      this.getEmployeeList()
    },

    // 删除员工
    async delEmp(id) {
      // 询问框
      const confirmRes = await this.$confirm('此操作将永久删除该文件, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).catch(err => err)

      // 处理取消
      if (confirmRes === 'cancel') return this.$message('您取消了删除')

      // 处理确定,调用接口
      const res = await delEmployee(id)

      // 如果分页只剩一条数据，删除以后，让页面减一
      if (this.employeesList.length === 1) {
        this.query.page--
        // 如果第一页只剩一条数据，删除以后，让page还原为1
        if (this.query.page <= 0) {
          this.query.page = 1
        }
      }

      // 给用户提示
      this.$message.success(res.message)
      // 刷新列表
      this.getEmployeeList()
    },

    // 格式化聘用形式
    formatter(row, column, cellValue, index) {
      const obj = Employeenum.hireType.find(item => item.id === Number(cellValue))
      return obj ? obj.value : '未知'
    },

    // 调用获取员工列表
    async getEmployeeList() {
      const res = await getEmployeeList(this.query)
      // console.log(res)
      this.employeesList = res.data.rows
      this.total = res.data.total
    },

    // 每页显示条数改变时触发
    handleSizeChange(newSize) {
      this.query.size = newSize
      this.getEmployeeList()
    },

    // 页码发生改变时触发
    handleCurrentChange(newPage) {
      this.query.page = newPage
      this.getEmployeeList()
    }
  }
}
</script>

<style lang="scss" scoped>
.el-pagination{
  text-align: center;
  margin-top: 20px;
}
.staffphoto{
  width: 100px;
  height: 100px;
  border-radius: 50%;
}
</style>
